<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Vue3 Composition API 快速上手 | 七里香</title><meta name="keywords" content="vue3"><meta name="author" content="william"><meta name="copyright" content="william"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="vue3知识梳理Vue3带来了什么 打包大小减少40% 初次渲染快55%，更新渲染快133% 内存减少54%  源码的升级 使用Proxy代替defineProperty实现响应式 重写虚拟DOM的实现和Tree-Shaking  拥抱TypeScript Vue3可以更好的支持TypeScript  新的特性 Composition API（组合API）  setup配置 ref与reactiv">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue3 Composition API 快速上手">
<meta property="og:url" content="http://yokeney.gitee.io/my-hexo-blog/2022/10/15/vue3/index.html">
<meta property="og:site_name" content="七里香">
<meta property="og:description" content="vue3知识梳理Vue3带来了什么 打包大小减少40% 初次渲染快55%，更新渲染快133% 内存减少54%  源码的升级 使用Proxy代替defineProperty实现响应式 重写虚拟DOM的实现和Tree-Shaking  拥抱TypeScript Vue3可以更好的支持TypeScript  新的特性 Composition API（组合API）  setup配置 ref与reactiv">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://yokeney.gitee.io/my-hexo-blog/img/vue3.png">
<meta property="article:published_time" content="2022-10-15T13:16:09.000Z">
<meta property="article:modified_time" content="2022-10-15T13:54:37.064Z">
<meta property="article:author" content="william">
<meta property="article:tag" content="vue3">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://yokeney.gitee.io/my-hexo-blog/img/vue3.png"><link rel="shortcut icon" href="/my-hexo-blog/img/index.ico"><link rel="canonical" href="http://yokeney.gitee.io/my-hexo-blog/2022/10/15/vue3/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/my-hexo-blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/my-hexo-blog/',
  algolia: undefined,
  localSearch: {"path":"/my-hexo-blog/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Vue3 Composition API 快速上手',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-10-15 21:54:37'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/my-hexo-blog/img/2.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/my-hexo-blog/archives/"><div class="headline">文章</div><div class="length-num">17</div></a><a href="/my-hexo-blog/tags/"><div class="headline">标签</div><div class="length-num">13</div></a><a href="/my-hexo-blog/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/my-hexo-blog/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 分类</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/my-hexo-blog/vueResources/"><i class="fa-fw iconfont icon-fenlei1"></i><span> vue</span></a></li><li><a class="site-page child" href="/my-hexo-blog/reactResources/"><i class="fa-fw iconfont icon-fenlei1"></i><span> react</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-shenghuo"></i><span> 后台</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/my-hexo-blog/nodeResources/"><i class="fa-fw iconfont icon-fenlei1"></i><span> node</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/my-hexo-blog/img/vue3.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/my-hexo-blog/">七里香</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/my-hexo-blog/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 分类</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/my-hexo-blog/vueResources/"><i class="fa-fw iconfont icon-fenlei1"></i><span> vue</span></a></li><li><a class="site-page child" href="/my-hexo-blog/reactResources/"><i class="fa-fw iconfont icon-fenlei1"></i><span> react</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-shenghuo"></i><span> 后台</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/my-hexo-blog/nodeResources/"><i class="fa-fw iconfont icon-fenlei1"></i><span> node</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Vue3 Composition API 快速上手</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-10-15T13:16:09.000Z" title="发表于 2022-10-15 21:16:09">2022-10-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-10-15T13:54:37.064Z" title="更新于 2022-10-15 21:54:37">2022-10-15</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Vue3 Composition API 快速上手"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="vue3知识梳理"><a href="#vue3知识梳理" class="headerlink" title="vue3知识梳理"></a>vue3知识梳理</h1><h4 id="Vue3带来了什么"><a href="#Vue3带来了什么" class="headerlink" title="Vue3带来了什么"></a>Vue3带来了什么</h4><ul>
<li>打包大小减少40%</li>
<li>初次渲染快55%，更新渲染快133%</li>
<li>内存减少54%</li>
</ul>
<h4 id="源码的升级"><a href="#源码的升级" class="headerlink" title="源码的升级"></a>源码的升级</h4><ul>
<li>使用Proxy代替defineProperty实现响应式</li>
<li>重写虚拟DOM的实现和Tree-Shaking</li>
</ul>
<h4 id="拥抱TypeScript"><a href="#拥抱TypeScript" class="headerlink" title="拥抱TypeScript"></a>拥抱TypeScript</h4><ul>
<li>Vue3可以更好的支持TypeScript</li>
</ul>
<h4 id="新的特性"><a href="#新的特性" class="headerlink" title="新的特性"></a>新的特性</h4><ol>
<li><p>Composition API（组合API）</p>
<ul>
<li>setup配置</li>
<li>ref与reactive</li>
<li>watch与watchEffect</li>
<li>provide与inject</li>
<li>……</li>
</ul>
</li>
<li><p>新的内置组件</p>
<ul>
<li>Fragment</li>
<li>Teleport</li>
<li>Suspense</li>
</ul>
<p>其他改变</p>
<ul>
<li>新的生命周期钩子</li>
<li>data 选项应始终被声明为一个函数</li>
<li>移除keyCode支持作为 v-on 的修饰符</li>
</ul>
<h2 id="Vue3-的优化"><a href="#Vue3-的优化" class="headerlink" title="Vue3 的优化"></a><strong>Vue3 的优化</strong></h2><p>本文源码版本是 Vue2 的，在 Vue3 里整个重写了 Diff 算法这一块东西，所以源码的话可以说基本是完全<strong>不一样</strong>的，但是要做的事还是一样的</p>
<p>关于 Vue3 的 Diff 完整源码解析还在撰稿中，过几天就发布了，这里先介绍一下相比 Vue2 优化的部分，尤大公布的数据就是 <code>update</code> 性能提升了 <code>1.3~2 倍</code>，<code>ssr</code> 性能提升了 <code>2~3 倍</code>，来看看都有哪些优化</p>
<ul>
<li>&#x3D;&#x3D;事件缓存：将事件缓存，可以理解为变成静态的了&#x3D;&#x3D;</li>
<li>&#x3D;&#x3D;添加静态标记：Vue2 是全量 Diff，Vue3 是静态标记 + 非全量 Diff&#x3D;&#x3D;</li>
<li>&#x3D;&#x3D;静态提升：创建静态节点时保存，后续直接复用&#x3D;&#x3D;</li>
<li>&#x3D;&#x3D;使用最长递增子序列优化了对比流程：Vue2 里在 updateChildren() 函数里对比变更，在 Vue3 里这一块的逻辑主要在 patchKeyedChildren() 函数里，具体看下面&#x3D;&#x3D;</li>
</ul>
<h3 id="事件缓存"><a href="#事件缓存" class="headerlink" title="事件缓存"></a><strong>事件缓存</strong></h3><p>比如这样一个有点击事件的按钮</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;button @click=<span class="string">&quot;handleClick&quot;</span>&gt;按钮&lt;/button&gt;</span><br></pre></td></tr></table></figure>

<p>来看下在 Vue3 被编译后的结果</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">render</span>(<span class="params">_ctx, _cache, $props, $setup, $data, $options</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> (<span class="title function_">_openBlock</span>(), <span class="title function_">_createElementBlock</span>(<span class="string">&quot;button&quot;</span>, &#123;</span><br><span class="line">    <span class="attr">onClick</span>: _cache[<span class="number">0</span>] || (_cache[<span class="number">0</span>] = <span class="function">(<span class="params">...args</span>) =&gt;</span> (_ctx.<span class="property">handleClick</span> &amp;&amp; _ctx.<span class="title function_">handleClick</span>(...args)))</span><br><span class="line">  &#125;, <span class="string">&quot;按钮&quot;</span>))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意看，onClick 会先读取缓存，如果缓存没有的话，就把传入的事件存到缓存里，都可以理解为变成静态节点了，优秀吧，而在 Vue2 中就没有缓存，就是动态的</p>
<h3 id="静态标记"><a href="#静态标记" class="headerlink" title="静态标记"></a><strong>静态标记</strong></h3><p>看一下静态标记是啥？</p>
<p>源码地址：<code>packages/shared/src/patchFlags.ts</code></p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">export const enum PatchFlags &#123;</span><br><span class="line">  TEXT = 1 ,  // 动态文本节点</span><br><span class="line">  CLASS = 1 &lt;&lt; 1,  // 2   动态class</span><br><span class="line">  STYLE = 1 &lt;&lt; 2,  // 4   动态style</span><br><span class="line">  PROPS = 1 &lt;&lt; 3,  // 8   除去class/style以外的动态属性</span><br><span class="line">  FULL_PROPS = 1 &lt;&lt; 4,       // 16  有动态key属性的节点，当key改变时，需进行完整的diff比较</span><br><span class="line">  HYDRATE_EVENTS = 1 &lt;&lt; 5,   // 32  有监听事件的节点</span><br><span class="line">  STABLE_FRAGMENT = 1 &lt;&lt; 6,  // 64  一个不会改变子节点顺序的fragment (一个组件内多个根元素就会用fragment包裹)</span><br><span class="line">  KEYED_FRAGMENT = 1 &lt;&lt; 7,   // 128 带有key属性的fragment或部分子节点有key</span><br><span class="line">  UNKEYEN_FRAGMENT = 1 &lt;&lt; 8, // 256  子节点没有key的fragment</span><br><span class="line">  NEED_PATCH = 1 &lt;&lt; 9,       // 512  一个节点只会进行非props比较</span><br><span class="line">  DYNAMIC_SLOTS = 1 &lt;&lt; 10,   // 1024   动态slot</span><br><span class="line">  HOISTED = -1,  // 静态节点 </span><br><span class="line">  BAIL = -2      // 表示 Diff 过程中不需要优化</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>先了解一下静态标记有什么用？看个图</p>
<p>在什么地方用到的呢？比如下面这样的代码</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;div id=&quot;app&quot;&gt;</span><br><span class="line">    &lt;div&gt;沐华&lt;/div&gt;</span><br><span class="line">    &lt;p&gt;&#123;&#123; age &#125;&#125;&lt;/p&gt;</span><br><span class="line">&lt;/div&gt;</span><br></pre></td></tr></table></figure>

<p>在 Vue2 中编译的结果是，有兴趣的可以自行安装 <code>vue-template-compiler</code> 自行测试</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">with(this)&#123;</span><br><span class="line">    return _c(</span><br><span class="line">      &#x27;div&#x27;,</span><br><span class="line">      &#123;attrs:&#123;&quot;id&quot;:&quot;app&quot;&#125;&#125;,</span><br><span class="line">      [ </span><br><span class="line">        _c(&#x27;div&#x27;,[_v(&quot;沐华&quot;)]),</span><br><span class="line">        _c(&#x27;p&#x27;,[_v(_s(age))])</span><br><span class="line">      ]</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在 Vue3 中编译的结果是这样的，有兴趣的可以**<a href="https://link.zhihu.com/?target=https://vue-next-template-explorer.netlify.app/">点击这里</a>**自行测试</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">const _hoisted_1 = &#123; id: &quot;app&quot; &#125;</span><br><span class="line">const _hoisted_2 = /*#__PURE__*/_createElementVNode(&quot;div&quot;, null, &quot;沐华&quot;, -1 /* HOISTED */)</span><br><span class="line"></span><br><span class="line">export function render(_ctx, _cache, $props, $setup, $data, $options) &#123;</span><br><span class="line">  return (_openBlock(), _createElementBlock(&quot;div&quot;, _hoisted_1, [</span><br><span class="line">    _hoisted_2,</span><br><span class="line">    _createElementVNode(&quot;p&quot;, null, _toDisplayString(_ctx.age), 1 /* TEXT */)</span><br><span class="line">  ]))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>看到上面编译结果中的 <code>-1</code> 和 <code>1</code> 了吗，这就是静态标记，这是在 Vue2 中没有的，patch 过程中就会判断这个标记来 Diff 优化流程，跳过一些静态节点对比</p>
<h3 id="静态提升"><a href="#静态提升" class="headerlink" title="静态提升"></a><strong>静态提升</strong></h3><p>其实还是拿上面 Vue2 和 Vue3 静态标记的例子，在 Vue2 里每当触发更新的时候，不管元素是否参与更新，每次都会全部重新创建，就是下面这一堆</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">with</span>(<span class="params"><span class="variable language_">this</span></span>)&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="title function_">_c</span>(</span><br><span class="line">      <span class="string">&#x27;div&#x27;</span>,</span><br><span class="line">      &#123;<span class="attr">attrs</span>:&#123;<span class="string">&quot;id&quot;</span>:<span class="string">&quot;app&quot;</span>&#125;&#125;,</span><br><span class="line">      [ </span><br><span class="line">        <span class="title function_">_c</span>(<span class="string">&#x27;div&#x27;</span>,[<span class="title function_">_v</span>(<span class="string">&quot;沐华&quot;</span>)]),</span><br><span class="line">        <span class="title function_">_c</span>(<span class="string">&#x27;p&#x27;</span>,[<span class="title function_">_v</span>(<span class="title function_">_s</span>(age))])</span><br><span class="line">      ]</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>而在 Vue3 中会把这个不参与更新的元素保存起来，只创建一次，之后在每次渲染的时候不停地复用，比如上面例子中的这个，静态的创建一次保存起来</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> _hoisted_1 = &#123; <span class="attr">id</span>: <span class="string">&quot;app&quot;</span> &#125;</span><br><span class="line"><span class="keyword">const</span> _hoisted_2 = <span class="comment">/*#__PURE__*/</span><span class="title function_">_createElementVNode</span>(<span class="string">&quot;div&quot;</span>, <span class="literal">null</span>, <span class="string">&quot;沐华&quot;</span>, -<span class="number">1</span> <span class="comment">/* HOISTED */</span>)</span><br></pre></td></tr></table></figure>

<p>然后每次更新 age 的时候，就只创建这个动态的内容，复用上面保存的静态内容</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">export function render(_ctx, _cache, $props, $setup, $data, $options) &#123;</span><br><span class="line">  return (_openBlock(), _createElementBlock(&quot;div&quot;, _hoisted_1, [</span><br><span class="line">    _hoisted_2,</span><br><span class="line">    _createElementVNode(&quot;p&quot;, null, _toDisplayString(_ctx.age), 1 /* TEXT */)</span><br><span class="line">  ]))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="patchKeyedChildren"><a href="#patchKeyedChildren" class="headerlink" title="patchKeyedChildren"></a><strong>patchKeyedChildren</strong></h3><p>在 Vue2 里 <code>updateChildren</code> 会进行</p>
<ul>
<li>头和头比</li>
<li>尾和尾比</li>
<li>头和尾比</li>
<li>尾和头比</li>
<li>都没有命中的对比</li>
</ul>
<p>在 Vue3 里 <code>patchKeyedChildren</code> 为</p>
<ul>
<li>头和头比</li>
<li>尾和尾比</li>
<li>基于最长递增子序列进行移动&#x2F;添加&#x2F;删除</li>
</ul>
<p>看个例子，比如</p>
<ul>
<li>老的 children：<code>[ a, b, c, d, e, f, g ]</code></li>
<li>新的 children：<code>[ a, b, f, c, d, e, h, g ]</code></li>
</ul>
<ol>
<li>先进行头和头比，发现不同就结束循环，得到 <code>[ a, b ]</code></li>
<li>再进行尾和尾比，发现不同就结束循环，得到 <code>[ g ]</code></li>
<li>再保存没有比较过的节点 <code>[ f, c, d, e, h ]</code>，并通过 newIndexToOldIndexMap 拿到在数组里对应的下标，生成数组 <code>[ 5, 2, 3, 4, -1 ]</code>，<code>-1</code> 是老数组里没有的就说明是新增</li>
<li>然后再拿取出数组里的最长递增子序列，也就是 <code>[ 2, 3, 4 ]</code> 对应的节点 <code>[ c, d, e ]</code></li>
<li>然后只需要把其他剩余的节点，基于 <code>[ c, d, e ]</code> 的位置进行移动&#x2F;新增&#x2F;删除就可以了</li>
</ol>
<p>使用最长递增子序列可以最大程度的减少 DOM 的移动，达到最少的 DOM 操作，有兴趣的话去 leet-code 第300题(最长递增子序列) 体验下</p>
</li>
</ol>
<h4 id="分析目录结构"><a href="#分析目录结构" class="headerlink" title="分析目录结构"></a>分析目录结构</h4><ul>
<li>main.js中的引入</li>
<li>在模板中vue3中是可以没有根标签了，这也是比较重要的改变</li>
<li>应用实例并不只限于一个。createApp API 允许你在同一个页面中创建多个共存的 Vue 应用，而且每个应用都拥有自己的用于配置和全局资源的作用域。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//main.js</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//引入的不再是Vue构造函数了，引入的是一个名为createApp的工厂函数</span></span><br><span class="line"><span class="keyword">import</span> &#123;createApp&#125; <span class="keyword">from</span> <span class="string">&#x27;vue</span></span><br><span class="line"><span class="string">import App from &#x27;</span>./<span class="title class_">App</span>.<span class="property">vue</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//创建应用实例对象-app(类似于之前vue2中的vm实例，但是app比vm更轻)</span></span><br><span class="line"><span class="title function_">createApp</span>(<span class="variable constant_">APP</span>).<span class="title function_">mount</span>(<span class="string">&#x27;#app&#x27;</span>)</span><br><span class="line"><span class="comment">//卸载就是unmount,卸载就没了</span></span><br><span class="line"><span class="comment">//createApp(APP).unmount(&#x27;#app&#x27;)</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//之前我们是这么写的，在vue3里面这一块就不支持了，会报错的，引入不到 import vue from &#x27;vue&#x27;; </span></span><br><span class="line"><span class="keyword">new</span> <span class="title class_">Vue</span>(&#123;</span><br><span class="line">	<span class="attr">render</span>:<span class="function">(<span class="params">h</span>) =&gt;</span> <span class="title function_">h</span>(<span class="title class_">App</span>)</span><br><span class="line">&#125;).$mount(<span class="string">&#x27;#app&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//多个应用实例</span></span><br><span class="line"><span class="keyword">const</span> app1 = <span class="title function_">createApp</span>(&#123;</span><br><span class="line">  <span class="comment">/* ... */</span></span><br><span class="line">&#125;)</span><br><span class="line">app1.<span class="title function_">mount</span>(<span class="string">&#x27;#container-1&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> app2 = <span class="title function_">createApp</span>(&#123;</span><br><span class="line">  <span class="comment">/* ... */</span></span><br><span class="line">&#125;)</span><br><span class="line">app2.<span class="title function_">mount</span>(<span class="string">&#x27;#container-2&#x27;</span>)</span><br></pre></td></tr></table></figure>

<h3 id="Vue3-Composition-API-快速上手"><a href="#Vue3-Composition-API-快速上手" class="headerlink" title="Vue3 Composition API 快速上手"></a>Vue3 Composition API 快速上手</h3><p><a target="_blank" rel="noopener" href="https://juejin.cn/post/7057725927739883551">链接</a></p>
<h1 id="创建Vue3-0工程"><a href="#创建Vue3-0工程" class="headerlink" title="创建Vue3.0工程"></a>创建Vue3.0工程</h1><h2 id="1-使用-vue-cli-创建"><a href="#1-使用-vue-cli-创建" class="headerlink" title="1.使用 vue-cli 创建"></a>1.使用 vue-cli 创建</h2><p>官方文档：<a target="_blank" rel="noopener" href="https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create">https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create</a></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">## 查看@vue/cli版本，确保@vue/cli版本在4.5.0以上</span><br><span class="line">vue --version</span><br><span class="line">## 安装或者升级你的@vue/cli</span><br><span class="line">npm install -g @vue/cli</span><br><span class="line">## 创建</span><br><span class="line">vue create vue_test</span><br><span class="line">## 启动</span><br><span class="line">cd vue_test</span><br><span class="line">npm run serve</span><br></pre></td></tr></table></figure>

<h2 id="2-使用-vite-创建"><a href="#2-使用-vite-创建" class="headerlink" title="2.使用 vite 创建"></a>2.使用 vite 创建</h2><p>官方文档：<a target="_blank" rel="noopener" href="https://v3.cn.vuejs.org/guide/installation.html#vite">https://v3.cn.vuejs.org/guide/installation.html#vite</a></p>
<p>vite官网：<a target="_blank" rel="noopener" href="https://vitejs.cn/">https://vitejs.cn</a></p>
<ul>
<li>什么是<a href="/Users/william/Documents/md/Vite.md">vite</a>？—— 新一代前端构建工具。</li>
<li>优势如下：<ul>
<li>开发环境中，无需打包操作，可快速的冷启动。</li>
<li>轻量快速的热重载（HMR）。</li>
<li>真正的按需编译，不再等待整个应用编译完成。</li>
</ul>
</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">## 创建工程</span><br><span class="line">npm init vite-app &lt;project-name&gt;</span><br><span class="line">## 进入工程目录</span><br><span class="line">cd &lt;project-name&gt;</span><br><span class="line">## 安装依赖</span><br><span class="line">npm install</span><br><span class="line">## 运行</span><br><span class="line">npm run dev</span><br></pre></td></tr></table></figure>

<h1 id="二、常用-Composition-API"><a href="#二、常用-Composition-API" class="headerlink" title="二、常用 Composition API"></a>二、常用 Composition API</h1><p>官方文档: <a target="_blank" rel="noopener" href="https://v3.cn.vuejs.org/guide/composition-api-introduction.html">https://v3.cn.vuejs.org/guide/composition-api-introduction.html</a></p>
<h2 id="1-拉开序幕的setup"><a href="#1-拉开序幕的setup" class="headerlink" title="1.拉开序幕的setup"></a>1.拉开序幕的setup</h2><ol>
<li>理解：Vue3.0中一个新的配置项，值为一个函数。</li>
<li>setup是所有<strong>Composition API（组合API）</strong><em>“ 表演的舞台 ”</em>。</li>
<li>组件中所用到的：数据、方法等等，均要配置在setup中。</li>
<li>setup函数的两种返回值：<ol>
<li>若返回一个对象，则对象中的属性、方法, 在模板中均可以直接使用。（重点关注！）</li>
<li>若返回一个渲染函数：则可以自定义渲染内容。（了解）</li>
</ol>
</li>
<li>注意点：<ol>
<li>尽量不要与Vue2.x配置混用<ul>
<li>Vue2.x配置（data、methos、computed…）中<strong>可以访问到</strong>setup中的属性、方法。</li>
<li>但在setup中<strong>不能访问到</strong>Vue2.x配置（data、methos、computed…）。</li>
<li>如果有重名, setup优先。</li>
</ul>
</li>
<li>setup不能是一个async函数，因为返回值不再是return的对象, 而是promise, 模板看不到return对象中的属性。（后期也可以返回一个Promise实例，但需要Suspense和异步组件的配合）</li>
</ol>
</li>
</ol>
<h2 id="2-ref函数"><a href="#2-ref函数" class="headerlink" title="2.ref函数"></a>2.ref函数</h2><ul>
<li>作用: 定义一个响应式的数据</li>
<li>语法: <code>const xxx = ref(initValue)</code><ul>
<li>创建一个包含响应式数据的<strong>引用对象（reference对象，简称ref对象）</strong>。</li>
<li>JS中操作数据： <code>xxx.value</code></li>
<li>模板中读取数据: 不需要.value，直接：<code>&lt;div&gt;&#123;&#123;xxx&#125;&#125;&lt;/div&gt;</code></li>
</ul>
</li>
<li>备注：<ul>
<li>接收的数据可以是：基本类型、也可以是对象类型。</li>
<li>基本类型的数据：响应式依然是靠<code>Object.defineProperty()</code>的<code>get</code>与<code>set</code>完成的。</li>
<li>对象类型的数据：内部 <em>“ 求助 ”</em> 了Vue3.0中的一个新函数—— <code>reactive</code>函数。</li>
</ul>
</li>
</ul>
<h2 id="3-reactive函数"><a href="#3-reactive函数" class="headerlink" title="3.reactive函数"></a>3.reactive函数</h2><ul>
<li>作用: 定义一个<strong>对象类型</strong>的响应式数据（基本类型不要用它，要用<code>ref</code>函数）</li>
<li>语法：<code>const 代理对象= reactive(源对象)</code>接收一个对象（或数组），返回一个<strong>代理对象（Proxy的实例对象，简称proxy对象）</strong></li>
<li>reactive定义的响应式数据是“深层次的”。</li>
<li>内部基于 ES6 的 Proxy 实现，通过代理对象操作源对象内部数据进行操作。</li>
</ul>
<h2 id="4-Vue3-0中的响应式原理"><a href="#4-Vue3-0中的响应式原理" class="headerlink" title="4.Vue3.0中的响应式原理"></a>4.Vue3.0中的响应式原理</h2><h3 id="vue2-x的响应式"><a href="#vue2-x的响应式" class="headerlink" title="vue2.x的响应式"></a>vue2.x的响应式</h3><ul>
<li><p>实现原理：</p>
<ul>
<li><p>对象类型：通过<code>Object.defineProperty()</code>对属性的读取、修改进行拦截（数据劫持）。</p>
</li>
<li><p>数组类型：通过重写更新数组的一系列方法来实现拦截。（对数组的变更方法进行了包裹）。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">Object</span>.<span class="title function_">defineProperty</span>(data, <span class="string">&#x27;count&#x27;</span>, &#123;</span><br><span class="line">    get () &#123;&#125;, </span><br><span class="line">    set () &#123;&#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>存在问题：</p>
<ul>
<li>新增属性、删除属性, 界面不会更新。</li>
<li>直接通过下标修改数组, 界面不会自动更新。</li>
</ul>
</li>
</ul>
<h3 id="Vue3-0的响应式"><a href="#Vue3-0的响应式" class="headerlink" title="Vue3.0的响应式"></a>Vue3.0的响应式</h3><ul>
<li><p>实现原理:</p>
<ul>
<li><p>通过Proxy（代理）: 拦截对象中任意属性的变化, 包括：属性值的读写、属性的添加、属性的删除等。</p>
</li>
<li><p>通过Reflect（反射）: 对源对象的属性进行操作。</p>
</li>
<li><p>MDN文档中描述的Proxy与Reflect：</p>
<ul>
<li><p>Proxy：<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy">https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy</a></p>
</li>
<li><p>Reflect：<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect">https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect</a></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="title class_">Proxy</span>(data, &#123;</span><br><span class="line">  <span class="comment">// 拦截读取属性值</span></span><br><span class="line">    get (target, prop) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="title class_">Reflect</span>.<span class="title function_">get</span>(target, prop)</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 拦截设置属性值或添加新属性</span></span><br><span class="line">    set (target, prop, value) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="title class_">Reflect</span>.<span class="title function_">set</span>(target, prop, value)</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 拦截删除属性</span></span><br><span class="line">    deleteProperty (target, prop) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="title class_">Reflect</span>.<span class="title function_">deleteProperty</span>(target, prop)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">proxy.<span class="property">name</span> = <span class="string">&#x27;tom&#x27;</span>   </span><br></pre></td></tr></table></figure></li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="5-reactive对比ref"><a href="#5-reactive对比ref" class="headerlink" title="5.reactive对比ref"></a>5.reactive对比ref</h2><ul>
<li>从定义数据角度对比：<ul>
<li>ref用来定义：<strong>基本类型数据</strong>。</li>
<li>reactive用来定义：<strong>对象（或数组）类型数据</strong>。</li>
<li>备注：ref也可以用来定义<strong>对象（或数组）类型数据</strong>, 它内部会自动通过<code>reactive</code>转为<strong>代理对象</strong>。</li>
</ul>
</li>
<li>从原理角度对比：<ul>
<li>ref通过<code>Object.defineProperty()</code>的<code>get</code>与<code>set</code>来实现响应式（数据劫持）。</li>
<li>reactive通过使用<strong>Proxy</strong>来实现响应式（数据劫持）, 并通过<strong>Reflect</strong>操作<strong>源对象</strong>内部的数据。</li>
</ul>
</li>
<li>从使用角度对比：<ul>
<li>ref定义的数据：操作数据<strong>需要</strong><code>.value</code>，读取数据时模板中直接读取<strong>不需要</strong><code>.value</code>。</li>
<li>reactive定义的数据：操作数据与读取数据：<strong>均不需要</strong><code>.value</code>。</li>
</ul>
</li>
</ul>
<h2 id="6-setup的两个注意点"><a href="#6-setup的两个注意点" class="headerlink" title="6.setup的两个注意点"></a>6.setup的两个注意点</h2><ul>
<li>setup执行的时机<ul>
<li>在beforeCreate之前执行一次，this是undefined。</li>
</ul>
</li>
<li>setup的参数<ul>
<li>props：值为对象，包含：组件外部传递过来，且组件内部声明接收了的属性。</li>
<li>context：上下文对象<ul>
<li>attrs: 值为对象，包含：组件外部传递过来，但没有在props配置中声明的属性, 相当于 <code>this.$attrs</code>。</li>
<li>slots: 收到的插槽内容, 相当于 <code>this.$slots</code>。</li>
<li>emit: 分发自定义事件的函数, 相当于 <code>this.$emit</code>。</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="7-计算属性与监视"><a href="#7-计算属性与监视" class="headerlink" title="7.计算属性与监视"></a>7.计算属性与监视</h2><h3 id="1-computed函数"><a href="#1-computed函数" class="headerlink" title="1.computed函数"></a>1.computed函数</h3><ul>
<li><p>与Vue2.x中computed配置功能一致</p>
</li>
<li><p>写法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;computed&#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="title function_">setup</span>(<span class="params"></span>)&#123;</span><br><span class="line">    ...</span><br><span class="line">  <span class="comment">//计算属性——简写</span></span><br><span class="line">    <span class="keyword">let</span> fullName = <span class="title function_">computed</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> person.<span class="property">firstName</span> + <span class="string">&#x27;-&#x27;</span> + person.<span class="property">lastName</span></span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="comment">//计算属性——完整</span></span><br><span class="line">    <span class="keyword">let</span> fullName = <span class="title function_">computed</span>(&#123;</span><br><span class="line">        <span class="title function_">get</span>(<span class="params"></span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> person.<span class="property">firstName</span> + <span class="string">&#x27;-&#x27;</span> + person.<span class="property">lastName</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="title function_">set</span>(<span class="params">value</span>)&#123;</span><br><span class="line">            <span class="keyword">const</span> nameArr = value.<span class="title function_">split</span>(<span class="string">&#x27;-&#x27;</span>)</span><br><span class="line">            person.<span class="property">firstName</span> = nameArr[<span class="number">0</span>]</span><br><span class="line">            person.<span class="property">lastName</span> = nameArr[<span class="number">1</span>]</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h3 id="2-watch函数"><a href="#2-watch函数" class="headerlink" title="2.watch函数"></a>2.watch函数</h3><ul>
<li><p>与Vue2.x中watch配置功能一致</p>
</li>
<li><p>两个小“坑”：</p>
<ul>
<li>监视reactive定义的响应式数据时：oldValue无法正确获取、强制开启了深度监视（deep配置失效）。</li>
<li>监视reactive定义的响应式数据中某个属性时：deep配置有效。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//情况一：监视ref定义的响应式数据</span></span><br><span class="line"><span class="title function_">watch</span>(sum,<span class="function">(<span class="params">newValue,oldValue</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;sum变化了&#x27;</span>,newValue,oldValue)</span><br><span class="line">&#125;,&#123;<span class="attr">immediate</span>:<span class="literal">true</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">//情况二：监视多个ref定义的响应式数据</span></span><br><span class="line"><span class="title function_">watch</span>([sum,msg],<span class="function">(<span class="params">newValue,oldValue</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;sum或msg变化了&#x27;</span>,newValue,oldValue)</span><br><span class="line">&#125;) </span><br><span class="line"></span><br><span class="line"><span class="comment">/* 情况三：监视reactive定义的响应式数据</span></span><br><span class="line"><span class="comment">      若watch监视的是reactive定义的响应式数据，则无法正确获得oldValue！！</span></span><br><span class="line"><span class="comment">      若watch监视的是reactive定义的响应式数据，则强制开启了深度监视 </span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="title function_">watch</span>(person,<span class="function">(<span class="params">newValue,oldValue</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;person变化了&#x27;</span>,newValue,oldValue)</span><br><span class="line">&#125;,&#123;<span class="attr">immediate</span>:<span class="literal">true</span>,<span class="attr">deep</span>:<span class="literal">false</span>&#125;) <span class="comment">//此处的deep配置不再奏效</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//情况四：监视reactive定义的响应式数据中的某个属性</span></span><br><span class="line"><span class="title function_">watch</span>(<span class="function">()=&gt;</span>person.<span class="property">job</span>,<span class="function">(<span class="params">newValue,oldValue</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;person的job变化了&#x27;</span>,newValue,oldValue)</span><br><span class="line">&#125;,&#123;<span class="attr">immediate</span>:<span class="literal">true</span>,<span class="attr">deep</span>:<span class="literal">true</span>&#125;) </span><br><span class="line"></span><br><span class="line"><span class="comment">//情况五：监视reactive定义的响应式数据中的某些属性</span></span><br><span class="line"><span class="title function_">watch</span>([<span class="function">()=&gt;</span>person.<span class="property">job</span>,<span class="function">()=&gt;</span>person.<span class="property">name</span>],<span class="function">(<span class="params">newValue,oldValue</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;person的job变化了&#x27;</span>,newValue,oldValue)</span><br><span class="line">&#125;,&#123;<span class="attr">immediate</span>:<span class="literal">true</span>,<span class="attr">deep</span>:<span class="literal">true</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">//特殊情况</span></span><br><span class="line"><span class="title function_">watch</span>(<span class="function">()=&gt;</span>person.<span class="property">job</span>,<span class="function">(<span class="params">newValue,oldValue</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;person的job变化了&#x27;</span>,newValue,oldValue)</span><br><span class="line">&#125;,&#123;<span class="attr">deep</span>:<span class="literal">true</span>&#125;) <span class="comment">//此处由于监视的是reactive素定义的对象中的某个属性，所以deep配置有效</span></span><br></pre></td></tr></table></figure></li>
</ul>
<h3 id="3-watchEffect函数"><a href="#3-watchEffect函数" class="headerlink" title="3.watchEffect函数"></a>3.watchEffect函数</h3><ul>
<li><p>watch的套路是：既要指明监视的属性，也要指明监视的回调。</p>
</li>
<li><p>watchEffect的套路是：不用指明监视哪个属性，监视的回调中用到哪个属性，那就监视哪个属性。</p>
</li>
<li><p>watchEffect有点像computed：</p>
<ul>
<li>但computed注重的计算出来的值（回调函数的返回值），所以必须要写返回值。</li>
<li>而watchEffect更注重的是过程（回调函数的函数体），所以不用写返回值。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//watchEffect所指定的回调中用到的数据只要发生变化，则直接重新执行回调。</span></span><br><span class="line"><span class="title function_">watchEffect</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">const</span> x1 = sum.<span class="property">value</span></span><br><span class="line">    <span class="keyword">const</span> x2 = person.<span class="property">age</span></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;watchEffect配置的回调执行了&#x27;</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="8-生命周期"><a href="#8-生命周期" class="headerlink" title="8.生命周期"></a>8.生命周期</h2><p><strong>vue2.x的生命周期</strong></p>
<p><strong>vue3.0的生命周期</strong></p>
<p>1</p>
<ul>
<li>Vue3.0中可以继续使用Vue2.x中的生命周期钩子，但有有两个被更名：<ul>
<li><code>beforeDestroy</code>改名为 <code>beforeUnmount</code></li>
<li><code>destroyed</code>改名为 <code>unmounted</code></li>
</ul>
</li>
<li>Vue3.0也提供了 Composition API 形式的生命周期钩子，与Vue2.x中钩子对应关系如下：<ul>
<li><strong><code>beforeCreate</code>&#x3D;&#x3D;&#x3D;&gt;<code>setup()</code></strong></li>
<li><strong><code>created</code>&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&gt;<code>setup()</code></strong></li>
<li><strong><code>beforeMount</code> &#x3D;&#x3D;&#x3D;&gt;<code>onBeforeMount</code></strong></li>
<li><strong><code>mounted</code>&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&gt;<code>onMounted</code></strong></li>
<li><strong><code>beforeUpdate</code>&#x3D;&#x3D;&#x3D;&gt;<code>onBeforeUpdate</code></strong></li>
<li><strong><code>updated</code> &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&gt;<code>onUpdated</code></strong></li>
<li><strong><code>beforeUnmount</code> &#x3D;&#x3D;&gt;<code>onBeforeUnmount</code></strong></li>
<li><strong><code>unmounted</code> &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&gt;<code>onUnmounted</code></strong></li>
</ul>
</li>
</ul>
<h2 id="9-自定义hook函数"><a href="#9-自定义hook函数" class="headerlink" title="9.自定义hook函数"></a>9.自定义hook函数</h2><ul>
<li>什么是hook？—— 本质是一个函数，把setup函数中使用的Composition API进行了封装。</li>
<li>类似于vue2.x中的mixin。</li>
<li>自定义hook的优势: 复用代码, 让setup中的逻辑更清楚易懂。</li>
</ul>
<h2 id="10-toRef"><a href="#10-toRef" class="headerlink" title="10.toRef"></a>10.toRef</h2><ul>
<li><p>作用：创建一个 ref 对象，其value值指向另一个对象中的某个属性。</p>
</li>
<li><p>语法：<code>const name = toRef(person,&#39;name&#39;)</code></p>
</li>
<li><p>应用: 要将响应式对象中的某个属性单独提供给外部使用时。</p>
</li>
<li><p>扩展：<code>toRefs</code> 与<code>toRef</code>功能一致，但可以批量创建多个 ref 对象，语法：<code>toRefs(person)</code></p>
</li>
</ul>
<h1 id="其它-Composition-API"><a href="#其它-Composition-API" class="headerlink" title="其它 Composition API"></a>其它 Composition API</h1><h2 id="1-shallowReactive-与-shallowRef"><a href="#1-shallowReactive-与-shallowRef" class="headerlink" title="1.shallowReactive 与 shallowRef"></a>1.shallowReactive 与 shallowRef</h2><ul>
<li>shallowReactive：只处理对象最外层属性的响应式（浅响应式）。</li>
<li>shallowRef：只处理基本数据类型的响应式, 不进行对象的响应式处理。</li>
<li>什么时候使用?<ul>
<li>如果有一个对象数据，结构比较深, 但变化时只是外层属性变化 &#x3D;&#x3D;&#x3D;&gt; shallowReactive。</li>
<li>如果有一个对象数据，后续功能不会修改该对象中的属性，而是生新的对象来替换 &#x3D;&#x3D;&#x3D;&gt; shallowRef。</li>
</ul>
</li>
</ul>
<h2 id="2-readonly-与-shallowReadonly"><a href="#2-readonly-与-shallowReadonly" class="headerlink" title="2.readonly 与 shallowReadonly"></a>2.readonly 与 shallowReadonly</h2><ul>
<li>readonly: 让一个响应式数据变为只读的（深只读）。</li>
<li>shallowReadonly：让一个响应式数据变为只读的（浅只读）。</li>
<li>应用场景: 不希望数据被修改时。</li>
</ul>
<h2 id="3-toRaw-与-markRaw"><a href="#3-toRaw-与-markRaw" class="headerlink" title="3.toRaw 与 markRaw"></a>3.toRaw 与 markRaw</h2><ul>
<li>toRaw：<ul>
<li>作用：将一个由<code>reactive</code>生成的<strong>响应式对象</strong>转为<strong>普通对象</strong>。</li>
<li>使用场景：用于读取响应式对象对应的普通对象，对这个普通对象的所有操作，不会引起页面更新。</li>
</ul>
</li>
<li>markRaw：<ul>
<li>作用：标记一个对象，使其永远不会再成为响应式对象。</li>
<li>应用场景:<ol>
<li>有些值不应被设置为响应式的，例如复杂的第三方类库等。</li>
<li>当渲染具有不可变数据源的大列表时，跳过响应式转换可以提高性能。</li>
</ol>
</li>
</ul>
</li>
</ul>
<h2 id="4-customRef"><a href="#4-customRef" class="headerlink" title="4.customRef"></a>4.customRef</h2><ul>
<li><p>作用：创建一个自定义的 ref，并对其依赖项跟踪和更新触发进行显式控制。</p>
</li>
<li><p>实现防抖效果：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  <span class="language-xml"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">v-model</span>=<span class="string">&quot;keyword&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">h3</span>&gt;</span>&#123;&#123;keyword&#125;&#125;<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">  <span class="keyword">import</span> &#123;ref,customRef&#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">  <span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="attr">name</span>:<span class="string">&#x27;Demo&#x27;</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="title function_">setup</span>(<span class="params"></span>)&#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="comment">// let keyword = ref(&#x27;hello&#x27;) //使用Vue准备好的内置ref</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="comment">//自定义一个myRef</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">function</span> <span class="title function_">myRef</span>(<span class="params">value,delay</span>)&#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">let</span> timer</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="comment">//通过customRef去实现自定义</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">return</span> <span class="title function_">customRef</span>(<span class="function">(<span class="params">track,trigger</span>)=&gt;</span>&#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">return</span>&#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="title function_">get</span>(<span class="params"></span>)&#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              <span class="title function_">track</span>() <span class="comment">//告诉Vue这个value值是需要被“追踪”的</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              <span class="keyword">return</span> value</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            &#125;,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="title function_">set</span>(<span class="params">newValue</span>)&#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              <span class="built_in">clearTimeout</span>(timer)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              timer = <span class="built_in">setTimeout</span>(<span class="function">()=&gt;</span>&#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                value = newValue</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="title function_">trigger</span>() <span class="comment">//告诉Vue去更新界面</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              &#125;,delay)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">let</span> keyword = <span class="title function_">myRef</span>(<span class="string">&#x27;hello&#x27;</span>,<span class="number">500</span>) <span class="comment">//使用程序员自定义的ref</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">return</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        keyword</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">  &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="5-provide-与-inject"><a href="#5-provide-与-inject" class="headerlink" title="5.provide 与 inject"></a>5.provide 与 inject</h2><p><img src="https://v3.cn.vuejs.org/images/components_provide.png" alt="img"></p>
<ul>
<li><p>作用：实现<strong>祖与后代组件间</strong>通信</p>
</li>
<li><p>套路：父组件有一个 <code>provide</code> 选项来提供数据，后代组件有一个 <code>inject</code> 选项来开始使用这些数据</p>
</li>
<li><p>具体写法：</p>
<ol>
<li><p>祖组件中：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">setup</span>(<span class="params"></span>)&#123;</span><br><span class="line">  ......</span><br><span class="line">    <span class="keyword">let</span> car = <span class="title function_">reactive</span>(&#123;<span class="attr">name</span>:<span class="string">&#x27;奔驰&#x27;</span>,<span class="attr">price</span>:<span class="string">&#x27;40万&#x27;</span>&#125;)</span><br><span class="line">    <span class="title function_">provide</span>(<span class="string">&#x27;car&#x27;</span>,car)</span><br><span class="line">    ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>后代组件中：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">setup</span>(<span class="params">props,context</span>)&#123;</span><br><span class="line">  ......</span><br><span class="line">    <span class="keyword">const</span> car = <span class="title function_">inject</span>(<span class="string">&#x27;car&#x27;</span>)</span><br><span class="line">    <span class="keyword">return</span> &#123;car&#125;</span><br><span class="line">  ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ol>
</li>
</ul>
<h2 id="6-响应式数据的判断"><a href="#6-响应式数据的判断" class="headerlink" title="6.响应式数据的判断"></a>6.响应式数据的判断</h2><ul>
<li>isRef: 检查一个值是否为一个 ref 对象</li>
<li>isReactive: 检查一个对象是否是由 <code>reactive</code> 创建的响应式代理</li>
<li>isReadonly: 检查一个对象是否是由 <code>readonly</code> 创建的只读代理</li>
<li>isProxy: 检查一个对象是否是由 <code>reactive</code> 或者 <code>readonly</code> 方法创建的代理</li>
</ul>
<h1 id="Composition-API-的优势"><a href="#Composition-API-的优势" class="headerlink" title="Composition API 的优势"></a>Composition API 的优势</h1><h2 id="1-Options-API-存在的问题"><a href="#1-Options-API-存在的问题" class="headerlink" title="1.Options API 存在的问题"></a>1.Options API 存在的问题</h2><p>使用传统OptionsAPI中，新增或者修改一个需求，就需要分别在data，methods，computed里修改 。</p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f84e4e2c02424d9a99862ade0a2e4114~tplv-k3u1fbpfcp-watermark.image" alt="img"></p>
<p><img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/e5ac7e20d1784887a826f6360768a368~tplv-k3u1fbpfcp-watermark.image" alt="img"></p>
<h2 id="2-Composition-API-的优势"><a href="#2-Composition-API-的优势" class="headerlink" title="2.Composition API 的优势"></a>2.Composition API 的优势</h2><p>我们可以更加优雅的组织我们的代码，函数。让相关功能的代码更加有序的组织在一起。</p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/bc0be8211fc54b6c941c036791ba4efe~tplv-k3u1fbpfcp-watermark.image" alt="img"> </p>
<p><img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6cc55165c0e34069a75fe36f8712eb80~tplv-k3u1fbpfcp-watermark.image" alt="img"> </p>
<p>五、新的组件</p>
<h2 id="1-Fragment"><a href="#1-Fragment" class="headerlink" title="1.Fragment"></a>1.Fragment</h2><ul>
<li>在Vue2中: 组件必须有一个根标签</li>
<li>在Vue3中: 组件可以没有根标签, 内部会将多个标签包含在一个Fragment虚拟元素中</li>
<li>好处: 减少标签层级, 减小内存占用</li>
</ul>
<h2 id="2-Teleport"><a href="#2-Teleport" class="headerlink" title="2.Teleport"></a>2.Teleport</h2><ul>
<li><p>什么是Teleport？—— <code>Teleport</code> 是一种能够将我们的<strong>组件html结构</strong>移动到指定位置的技术。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;teleport to=<span class="string">&quot;移动位置&quot;</span>&gt;</span><br><span class="line">  <span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">v-if</span>=<span class="string">&quot;isShow&quot;</span> <span class="attr">class</span>=<span class="string">&quot;mask&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;dialog&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">h3</span>&gt;</span>我是一个弹窗<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span> @<span class="attr">click</span>=<span class="string">&quot;isShow = false&quot;</span>&gt;</span>关闭弹窗<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">&lt;/teleport&gt;</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="3-Suspense"><a href="#3-Suspense" class="headerlink" title="3.Suspense"></a>3.Suspense</h2><ul>
<li><p>等待异步组件时渲染一些额外内容，让应用有更好的用户体验</p>
</li>
<li><p>使用步骤：</p>
<ul>
<li><p>异步引入组件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;defineAsyncComponent&#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">Child</span> = <span class="title function_">defineAsyncComponent</span>(<span class="function">()=&gt;</span><span class="title function_">import</span>(<span class="string">&#x27;./components/Child.vue&#x27;</span>))</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用<code>Suspense</code>包裹组件，并配置好<code>default</code> 与 <code>fallback</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  <span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;app&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">h3</span>&gt;</span>我是App组件<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">Suspense</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">template</span> <span class="attr">v-slot:default</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">Child</span>/&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">template</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">template</span> <span class="attr">v-slot:fallback</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">h3</span>&gt;</span>加载中.....<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">template</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">Suspense</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">&lt;/template&gt;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
</ul>
<h1 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h1><h2 id="1-全局API的转移"><a href="#1-全局API的转移" class="headerlink" title="1.全局API的转移"></a>1.全局API的转移</h2><ul>
<li><p>Vue 2.x 有许多全局 API 和配置。</p>
<ul>
<li><p>例如：注册全局组件、注册全局指令等。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">//注册全局组件</span><br><span class="line">Vue.component(&#x27;MyButton&#x27;, &#123;</span><br><span class="line">  data: () =&gt; (&#123;</span><br><span class="line">    count: 0</span><br><span class="line">  &#125;),</span><br><span class="line">  template: &#x27;&lt;button @click=&quot;count++&quot;&gt;Clicked &#123;&#123; count &#125;&#125; times.&lt;/button&gt;&#x27;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">//注册全局指令</span><br><span class="line">Vue.directive(&#x27;focus&#x27;, &#123;</span><br><span class="line">  inserted: el =&gt; el.focus()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>Vue3.0中对这些API做出了调整：</p>
<ul>
<li><p>将全局的API，即：<code>Vue.xxx</code>调整到应用实例（<code>app</code>）上</p>
<table>
<thead>
<tr>
<th>2.x 全局 API（<code>Vue</code>）</th>
<th>3.x 实例 API (<code>app</code>)</th>
</tr>
</thead>
<tbody><tr>
<td>Vue.config.xxxx</td>
<td>app.config.xxxx</td>
</tr>
<tr>
<td>Vue.config.productionTip</td>
<td><strong>移除</strong></td>
</tr>
<tr>
<td>Vue.component</td>
<td>app.component</td>
</tr>
<tr>
<td>Vue.directive</td>
<td>app.directive</td>
</tr>
<tr>
<td>Vue.mixin</td>
<td>app.mixin</td>
</tr>
<tr>
<td>Vue.use</td>
<td>app.use</td>
</tr>
<tr>
<td>Vue.prototype</td>
<td>app.config.globalProperties</td>
</tr>
</tbody></table>
</li>
</ul>
</li>
</ul>
<h2 id="其他改变"><a href="#其他改变" class="headerlink" title="其他改变"></a>其他改变</h2><ul>
<li><p>data选项应始终被声明为一个函数。</p>
</li>
<li><p>过度类名的更改：</p>
<ul>
<li><p>Vue2.x写法</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-class">.v-enter</span>,</span><br><span class="line"><span class="selector-class">.v-leave-to</span> &#123;</span><br><span class="line">  <span class="attribute">opacity</span>: <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-class">.v-leave</span>,</span><br><span class="line"><span class="selector-class">.v-enter-to</span> &#123;</span><br><span class="line">  <span class="attribute">opacity</span>: <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>Vue3.x写法</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-class">.v-enter-from</span>,</span><br><span class="line"><span class="selector-class">.v-leave-to</span> &#123;</span><br><span class="line">  <span class="attribute">opacity</span>: <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.v-leave-from</span>,</span><br><span class="line"><span class="selector-class">.v-enter-to</span> &#123;</span><br><span class="line">  <span class="attribute">opacity</span>: <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p><strong>移除</strong>keyCode作为 v-on 的修饰符，同时也不再支持<code>config.keyCodes</code></p>
</li>
<li><p><strong>移除</strong><code>v-on.native</code>修饰符</p>
<ul>
<li><p>父组件中绑定事件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;my-component</span><br><span class="line">  v-<span class="attr">on</span>:close=<span class="string">&quot;handleComponentEvent&quot;</span></span><br><span class="line">  v-<span class="attr">on</span>:click=<span class="string">&quot;handleNativeClickEvent&quot;</span></span><br><span class="line">/&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>子组件中声明自定义事件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">  <span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    <span class="attr">emits</span>: [<span class="string">&#x27;close&#x27;</span>]</span><br><span class="line">  &#125;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p><strong>移除</strong>过滤器（filter）</p>
<blockquote>
<p>过滤器虽然这看起来很方便，但它需要一个自定义语法，打破大括号内表达式是 “只是 JavaScript” 的假设，这不仅有学习成本，而且有实现成本！建议用方法调用或计算属性去替换过滤器。</p>
</blockquote>
<h2 id="vue原理解析"><a href="#vue原理解析" class="headerlink" title="vue原理解析"></a>vue原理解析</h2><h2 id="1-准备"><a href="#1-准备" class="headerlink" title="1. 准备"></a>1. 准备</h2></li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>[].<span class="property">slice</span>.<span class="title function_">call</span>(lis): 将伪数组转换为真数组</span><br><span class="line"><span class="number">2.</span>node.<span class="property">nodeType</span>: 得到节点类型</span><br><span class="line"><span class="number">3.</span><span class="title class_">Object</span>.<span class="title function_">defineProperty</span>(obj, propertyName, &#123;&#125;): 给对象添加/修改属性(指定描述符)</span><br><span class="line">	<span class="attr">configurable</span>: <span class="literal">true</span>/<span class="literal">false</span>  是否可以重新define</span><br><span class="line">	<span class="attr">enumerable</span>: <span class="literal">true</span>/<span class="literal">false</span> 是否可以枚举(<span class="keyword">for</span>..<span class="property">in</span> / <span class="title function_">keys</span>())</span><br><span class="line">	<span class="attr">value</span>: 指定初始值</span><br><span class="line">	<span class="attr">writable</span>: <span class="literal">true</span>/<span class="literal">false</span> value是否可以修改存取(访问)描述符</span><br><span class="line">	<span class="attr">get</span>: 函数, 用来得到当前属性值</span><br><span class="line">	<span class="attr">set</span>: 函数, 用来监视当前属性值的变化</span><br></pre></td></tr></table></figure>

<pre><code>  4.Object.keys(obj): 得到对象自身可枚举的属性名的数组
  5.DocumentFragment: 文档碎片(高效批量更新多个节点)
  6.obj.hasOwnProperty(prop): 判断prop是否是obj自身的属性
</code></pre>
<h2 id="2-数据代理-MVVM-js"><a href="#2-数据代理-MVVM-js" class="headerlink" title="2. 数据代理(MVVM.js)"></a>2. 数据代理(MVVM.js)</h2><pre><code>1.通过一个对象代理对另一个对象中属性的操作(读/写)

  2.通过vm对象来代理data对象中所有属性的操作
  3.好处: 更方便的操作data中的数据
  4.基本实现流程
    1). 通过Object.defineProperty()给vm添加与data对象的属性对应的属性描述符
    2). 所有添加的属性都包含getter/setter
    3). 在getter/setter内部去操作data中对应的属性数据
</code></pre>
<h2 id="3-模板解析-compile-js"><a href="#3-模板解析-compile-js" class="headerlink" title="3. 模板解析(compile.js)"></a>3. 模板解析(compile.js)</h2><pre><code>  1.模板解析的关键对象: compile对象
  2.模板解析的基本流程:
    1). 将el的所有子节点取出, 添加到一个新建的文档fragment对象中
    2). 对fragment中的所有层次子节点递归进行编译解析处理
        * 对表达式文本节点进行解析
        * 对元素节点的指令属性进行解析
            * 事件指令解析
            * 一般指令解析
      3). 将解析后的fragment添加到el中显示
3.解析表达式文本节点: textNode.textContent = value
      1). 根据正则对象得到匹配出的表达式字符串: 子匹配/RegExp.$1
      2). 从data中取出表达式对应的属性值
      3). 将属性值设置为文本节点的textContent
4.事件指令解析: elementNode.addEventListener(事件名, 回调函数.bind(vm))
    v-on:click=&quot;test&quot;
      1). 从指令名中取出事件名
      2). 根据指令的值(表达式)从methods中得到对应的事件处理函数对象
      3). 给当前元素节点绑定指定事件名和回调函数的dom事件监听
      4). 指令解析完后, 移除此指令属性
5.一般指令解析: elementNode.xxx = value
      1). 得到指令名和指令值(表达式)
      2). 从data中根据表达式得到对应的值
      3). 根据指令名确定需要操作元素节点的什么属性
        * v-text---textContent属性
        * v-html---innerHTML属性
        * v-class--className属性
      4). 将得到的表达式的值设置到对应的属性上
      5). 移除元素的指令属性
</code></pre>
<h2 id="4-数据劫持–-gt-数据绑定"><a href="#4-数据劫持–-gt-数据绑定" class="headerlink" title="4. 数据劫持–&gt;数据绑定"></a>4. 数据劫持–&gt;数据绑定</h2><pre><code>1.数据绑定(model==&gt;View):
    1). 一旦更新了data中的某个属性数据, 所有界面上直接使用或间接使用了此属性的节点都会更新(更新)

  2.数据劫持
    1). 数据劫持是vue中用来实现数据绑定的一种技术
    2). 基本思想: 通过defineProperty()来监视data中所有属性(任意层次)数据的变化, 一旦变化就去更新界面
  3.四个重要对象
    1). Observer
        * 用来对data所有属性数据进行劫持的构造函数
      	* 给data中所有属性重新定义属性描述(get/set)
      	* 为data中的每个属性创建对应的dep对象
    2). Dep(Depend)
      	* data中的每个属性(所有层次)都对应一个dep对象
      	* 创建的时机:
        	* 在初始化define data中各个属性时创建对应的dep对象
        	* 在data中的某个属性值被设置为新的对象时
      	* 对象的结构
            &#123;
              id, // 每个dep都有一个唯一的id
              subs //包含n个对应watcher的数组(subscribes的简写)
            &#125;
        * subs属性说明
            * 当一个watcher被创建时, 内部会将当前watcher对象添加到对应的dep对象的subs中
            * 当此data属性的值发生改变时, 所有subs中的watcher都会收到更新的通知, 从而最终更新对应的界面
    3). Compile
        * 用来解析模板页面的对象的构造函数(一个实例)
        * 利用compile对象解析模板页面
        * 每解析一个表达式(非事件指令)都会创建一个对应的watcher对象, 并建立watcher与dep的关系
        * complie与watcher关系: 一对多的关系
    4). Watcher
      	* 模板中每个非事件指令或表达式都对应一个watcher对象
      	* 监视当前表达式数据的变化
      	* 创建的时机: 在初始化编译模板时
      	* 对象的组成
            &#123;
              vm,  //vm对象
              exp, //对应指令的表达式
              cb, //当表达式所对应的数据发生改变的回调函数
              value, //表达式当前的值
              depIds //表达式中各级属性所对应的dep对象的集合对象
                      //属性名为dep的id, 属性值为dep
            &#125;
        

    5). 总结: dep与watcher的关系: 多对多
        * 一个data中的属性对应对应一个dep, 一个dep中可能包含多个watcher(模板中有几个表达式使用到了属性)
        * 模板中一个非事件表达式对应一个watcher, 一个watcher中可能包含多个dep(表达式中包含了几个data属性)
        * 数据绑定使用到2个核心技术
            * defineProperty()
            * 消息订阅与发布

4.双向数据绑定
    1). 双向数据绑定是建立在单向数据绑定(model==&gt;View)的基础之上的
    2). 双向数据绑定的实现流程:
      	* 在解析v-model指令时, 给当前元素添加input监听
      	* 当input的value发生改变时, 将最新的值赋值给当前表达式所对应的data属性
</code></pre>
</article><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/my-hexo-blog/tags/vue3/">vue3</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/my-hexo-blog/2022/10/15/react%E5%8E%9F%E7%90%86/"><img class="prev-cover" src="/my-hexo-blog/img/reactfiber.png" onerror="onerror=null;src='/my-hexo-blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">react原理</div></div></a></div><div class="next-post pull-right"><a href="/my-hexo-blog/2022/10/15/nginxconfig/"><img class="next-cover" src="/my-hexo-blog/img/nginx.png" onerror="onerror=null;src='/my-hexo-blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Nginx配置前端http缓存</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/my-hexo-blog/img/2.png" onerror="this.onerror=null;this.src='/my-hexo-blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">william</div><div class="author-info__description"> 青山不改，绿水长流</div></div><div class="card-info-data site-data is-center"><a href="/my-hexo-blog/archives/"><div class="headline">文章</div><div class="length-num">17</div></a><a href="/my-hexo-blog/tags/"><div class="headline">标签</div><div class="length-num">13</div></a><a href="/my-hexo-blog/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/yokeney"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/yokeney" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="/my-hexo-blog/965660471@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">加油</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#vue3%E7%9F%A5%E8%AF%86%E6%A2%B3%E7%90%86"><span class="toc-number">1.</span> <span class="toc-text">vue3知识梳理</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Vue3%E5%B8%A6%E6%9D%A5%E4%BA%86%E4%BB%80%E4%B9%88"><span class="toc-number">1.0.0.1.</span> <span class="toc-text">Vue3带来了什么</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%BA%90%E7%A0%81%E7%9A%84%E5%8D%87%E7%BA%A7"><span class="toc-number">1.0.0.2.</span> <span class="toc-text">源码的升级</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%8B%A5%E6%8A%B1TypeScript"><span class="toc-number">1.0.0.3.</span> <span class="toc-text">拥抱TypeScript</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B0%E7%9A%84%E7%89%B9%E6%80%A7"><span class="toc-number">1.0.0.4.</span> <span class="toc-text">新的特性</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Vue3-%E7%9A%84%E4%BC%98%E5%8C%96"><span class="toc-number">1.1.</span> <span class="toc-text">Vue3 的优化</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BA%8B%E4%BB%B6%E7%BC%93%E5%AD%98"><span class="toc-number">1.1.1.</span> <span class="toc-text">事件缓存</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%99%E6%80%81%E6%A0%87%E8%AE%B0"><span class="toc-number">1.1.2.</span> <span class="toc-text">静态标记</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%99%E6%80%81%E6%8F%90%E5%8D%87"><span class="toc-number">1.1.3.</span> <span class="toc-text">静态提升</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#patchKeyedChildren"><span class="toc-number">1.1.4.</span> <span class="toc-text">patchKeyedChildren</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%86%E6%9E%90%E7%9B%AE%E5%BD%95%E7%BB%93%E6%9E%84"><span class="toc-number">1.1.4.1.</span> <span class="toc-text">分析目录结构</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Vue3-Composition-API-%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B"><span class="toc-number">1.1.5.</span> <span class="toc-text">Vue3 Composition API 快速上手</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%88%9B%E5%BB%BAVue3-0%E5%B7%A5%E7%A8%8B"><span class="toc-number">2.</span> <span class="toc-text">创建Vue3.0工程</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E4%BD%BF%E7%94%A8-vue-cli-%E5%88%9B%E5%BB%BA"><span class="toc-number">2.1.</span> <span class="toc-text">1.使用 vue-cli 创建</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E4%BD%BF%E7%94%A8-vite-%E5%88%9B%E5%BB%BA"><span class="toc-number">2.2.</span> <span class="toc-text">2.使用 vite 创建</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E5%B8%B8%E7%94%A8-Composition-API"><span class="toc-number">3.</span> <span class="toc-text">二、常用 Composition API</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E6%8B%89%E5%BC%80%E5%BA%8F%E5%B9%95%E7%9A%84setup"><span class="toc-number">3.1.</span> <span class="toc-text">1.拉开序幕的setup</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-ref%E5%87%BD%E6%95%B0"><span class="toc-number">3.2.</span> <span class="toc-text">2.ref函数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-reactive%E5%87%BD%E6%95%B0"><span class="toc-number">3.3.</span> <span class="toc-text">3.reactive函数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-Vue3-0%E4%B8%AD%E7%9A%84%E5%93%8D%E5%BA%94%E5%BC%8F%E5%8E%9F%E7%90%86"><span class="toc-number">3.4.</span> <span class="toc-text">4.Vue3.0中的响应式原理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#vue2-x%E7%9A%84%E5%93%8D%E5%BA%94%E5%BC%8F"><span class="toc-number">3.4.1.</span> <span class="toc-text">vue2.x的响应式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Vue3-0%E7%9A%84%E5%93%8D%E5%BA%94%E5%BC%8F"><span class="toc-number">3.4.2.</span> <span class="toc-text">Vue3.0的响应式</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-reactive%E5%AF%B9%E6%AF%94ref"><span class="toc-number">3.5.</span> <span class="toc-text">5.reactive对比ref</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-setup%E7%9A%84%E4%B8%A4%E4%B8%AA%E6%B3%A8%E6%84%8F%E7%82%B9"><span class="toc-number">3.6.</span> <span class="toc-text">6.setup的两个注意点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7%E4%B8%8E%E7%9B%91%E8%A7%86"><span class="toc-number">3.7.</span> <span class="toc-text">7.计算属性与监视</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-computed%E5%87%BD%E6%95%B0"><span class="toc-number">3.7.1.</span> <span class="toc-text">1.computed函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-watch%E5%87%BD%E6%95%B0"><span class="toc-number">3.7.2.</span> <span class="toc-text">2.watch函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-watchEffect%E5%87%BD%E6%95%B0"><span class="toc-number">3.7.3.</span> <span class="toc-text">3.watchEffect函数</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-number">3.8.</span> <span class="toc-text">8.生命周期</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9-%E8%87%AA%E5%AE%9A%E4%B9%89hook%E5%87%BD%E6%95%B0"><span class="toc-number">3.9.</span> <span class="toc-text">9.自定义hook函数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10-toRef"><span class="toc-number">3.10.</span> <span class="toc-text">10.toRef</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%B6%E5%AE%83-Composition-API"><span class="toc-number">4.</span> <span class="toc-text">其它 Composition API</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-shallowReactive-%E4%B8%8E-shallowRef"><span class="toc-number">4.1.</span> <span class="toc-text">1.shallowReactive 与 shallowRef</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-readonly-%E4%B8%8E-shallowReadonly"><span class="toc-number">4.2.</span> <span class="toc-text">2.readonly 与 shallowReadonly</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-toRaw-%E4%B8%8E-markRaw"><span class="toc-number">4.3.</span> <span class="toc-text">3.toRaw 与 markRaw</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-customRef"><span class="toc-number">4.4.</span> <span class="toc-text">4.customRef</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-provide-%E4%B8%8E-inject"><span class="toc-number">4.5.</span> <span class="toc-text">5.provide 与 inject</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-%E5%93%8D%E5%BA%94%E5%BC%8F%E6%95%B0%E6%8D%AE%E7%9A%84%E5%88%A4%E6%96%AD"><span class="toc-number">4.6.</span> <span class="toc-text">6.响应式数据的判断</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Composition-API-%E7%9A%84%E4%BC%98%E5%8A%BF"><span class="toc-number">5.</span> <span class="toc-text">Composition API 的优势</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-Options-API-%E5%AD%98%E5%9C%A8%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-number">5.1.</span> <span class="toc-text">1.Options API 存在的问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-Composition-API-%E7%9A%84%E4%BC%98%E5%8A%BF"><span class="toc-number">5.2.</span> <span class="toc-text">2.Composition API 的优势</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-Fragment"><span class="toc-number">5.3.</span> <span class="toc-text">1.Fragment</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-Teleport"><span class="toc-number">5.4.</span> <span class="toc-text">2.Teleport</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-Suspense"><span class="toc-number">5.5.</span> <span class="toc-text">3.Suspense</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%B6%E4%BB%96"><span class="toc-number">6.</span> <span class="toc-text">其他</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E5%85%A8%E5%B1%80API%E7%9A%84%E8%BD%AC%E7%A7%BB"><span class="toc-number">6.1.</span> <span class="toc-text">1.全局API的转移</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%B6%E4%BB%96%E6%94%B9%E5%8F%98"><span class="toc-number">6.2.</span> <span class="toc-text">其他改变</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#vue%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90"><span class="toc-number">6.3.</span> <span class="toc-text">vue原理解析</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E5%87%86%E5%A4%87"><span class="toc-number">6.4.</span> <span class="toc-text">1. 准备</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E6%95%B0%E6%8D%AE%E4%BB%A3%E7%90%86-MVVM-js"><span class="toc-number">6.5.</span> <span class="toc-text">2. 数据代理(MVVM.js)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E6%A8%A1%E6%9D%BF%E8%A7%A3%E6%9E%90-compile-js"><span class="toc-number">6.6.</span> <span class="toc-text">3. 模板解析(compile.js)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E6%95%B0%E6%8D%AE%E5%8A%AB%E6%8C%81%E2%80%93-gt-%E6%95%B0%E6%8D%AE%E7%BB%91%E5%AE%9A"><span class="toc-number">6.7.</span> <span class="toc-text">4. 数据劫持–&gt;数据绑定</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/my-hexo-blog/2023/05/26/VUE3%E9%9B%86%E6%88%90%E4%BC%81%E4%B8%9A%E7%BA%A7%E5%90%8E%E5%8F%B0%E9%80%9A%E7%94%A8%E8%A7%84%E8%8C%83%E6%A8%A1%E7%89%88/" title="VUE3集成企业级后台通用规范模版"><img src="/my-hexo-blog/img/1.png" onerror="this.onerror=null;this.src='/my-hexo-blog/img/404.jpg'" alt="VUE3集成企业级后台通用规范模版"/></a><div class="content"><a class="title" href="/my-hexo-blog/2023/05/26/VUE3%E9%9B%86%E6%88%90%E4%BC%81%E4%B8%9A%E7%BA%A7%E5%90%8E%E5%8F%B0%E9%80%9A%E7%94%A8%E8%A7%84%E8%8C%83%E6%A8%A1%E7%89%88/" title="VUE3集成企业级后台通用规范模版">VUE3集成企业级后台通用规范模版</a><time datetime="2023-05-26T13:17:48.000Z" title="发表于 2023-05-26 21:17:48">2023-05-26</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/my-hexo-blog/2023/04/24/%E6%B2%A1%E7%9C%8B%E8%BF%99%E7%AF%87%E6%96%87%E7%AB%A0%E4%B9%8B%E5%89%8D%E5%8E%9F%E6%9D%A5%E6%88%91%E5%AF%B9react18%E4%B8%80%E7%9F%A5%E5%8D%8A%E8%A7%A3/" title="没看这篇文章之前原来我对react18一知半解"><img src="/my-hexo-blog/img/react.png" onerror="this.onerror=null;this.src='/my-hexo-blog/img/404.jpg'" alt="没看这篇文章之前原来我对react18一知半解"/></a><div class="content"><a class="title" href="/my-hexo-blog/2023/04/24/%E6%B2%A1%E7%9C%8B%E8%BF%99%E7%AF%87%E6%96%87%E7%AB%A0%E4%B9%8B%E5%89%8D%E5%8E%9F%E6%9D%A5%E6%88%91%E5%AF%B9react18%E4%B8%80%E7%9F%A5%E5%8D%8A%E8%A7%A3/" title="没看这篇文章之前原来我对react18一知半解">没看这篇文章之前原来我对react18一知半解</a><time datetime="2023-04-24T09:11:02.000Z" title="发表于 2023-04-24 17:11:02">2023-04-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/my-hexo-blog/2023/04/24/%E5%8F%B2%E4%B8%8A%E6%9C%80%E5%85%A8Vue3%E6%80%BB%E7%BB%93/" title="史上最全Vue3总结"><img src="/my-hexo-blog/img/1.png" onerror="this.onerror=null;this.src='/my-hexo-blog/img/404.jpg'" alt="史上最全Vue3总结"/></a><div class="content"><a class="title" href="/my-hexo-blog/2023/04/24/%E5%8F%B2%E4%B8%8A%E6%9C%80%E5%85%A8Vue3%E6%80%BB%E7%BB%93/" title="史上最全Vue3总结">史上最全Vue3总结</a><time datetime="2023-04-24T09:01:19.000Z" title="发表于 2023-04-24 17:01:19">2023-04-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/my-hexo-blog/2023/04/24/%E4%B8%8EReact18%E7%9A%84%E5%8C%BA%E5%88%AB%E6%B7%B1%E5%BA%A6%E8%A7%A3%E6%9E%90/" title="Vue与React18的区别深度解析"><img src="/my-hexo-blog/img/vue_vs-react.png" onerror="this.onerror=null;this.src='/my-hexo-blog/img/404.jpg'" alt="Vue与React18的区别深度解析"/></a><div class="content"><a class="title" href="/my-hexo-blog/2023/04/24/%E4%B8%8EReact18%E7%9A%84%E5%8C%BA%E5%88%AB%E6%B7%B1%E5%BA%A6%E8%A7%A3%E6%9E%90/" title="Vue与React18的区别深度解析">Vue与React18的区别深度解析</a><time datetime="2023-04-24T08:39:32.000Z" title="发表于 2023-04-24 16:39:32">2023-04-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/my-hexo-blog/2022/10/25/%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%A6%E4%BD%A0%E5%86%99%E4%B8%80%E4%B8%AAbabel/" title="手把手教你写babel插件"><img src="/my-hexo-blog/img/babel.webp" onerror="this.onerror=null;this.src='/my-hexo-blog/img/404.jpg'" alt="手把手教你写babel插件"/></a><div class="content"><a class="title" href="/my-hexo-blog/2022/10/25/%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%A6%E4%BD%A0%E5%86%99%E4%B8%80%E4%B8%AAbabel/" title="手把手教你写babel插件">手把手教你写babel插件</a><time datetime="2022-10-25T01:10:14.000Z" title="发表于 2022-10-25 09:10:14">2022-10-25</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/my-hexo-blog/img/1.png')"><div id="footer-wrap"><div class="copyright">&copy;2018 - 2023 By william</div><div class="footer_custom_text">关山难越，谁悲失路之人</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/my-hexo-blog/js/utils.js"></script><script src="/my-hexo-blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="/my-hexo-blog/js/search/local-search.js"></script><div class="js-pjax"></div><div class="aplayer no-destroy" data-id="22712173" data-server="netease" data-mini="true" data-type="song" data-autoplay="false" data-lrcType="-1"> </div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>